package com.loren.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.sql.SQLException;
import java.util.Collections;

/**
 * 配置默认的数据源
 */
@Configuration
public class DefaultDataSourceConfig {

    @Value("${custom.default.datasource.db-url}")
    private String databaseUrl;

    @Value("${custom.default.datasource.db-user-name}")
    private String dbUserName;

    @Value("${custom.default.datasource.db-password}")
    private String dbPassword;

    @Autowired
    JpaProperties jpaProperties;

    @Bean
    public DynamicDatasouce dynamicDatasouce() throws SQLException {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl(this.databaseUrl);
        dataSource.setUsername(this.dbUserName);
        dataSource.setPassword(this.dbPassword);
        dataSource.setMaxActive(20);
        dataSource.setMaxWait(10000);
        dataSource.setValidationQuery("SELECT 1");
        dataSource.setFilters("config, stat");
        dataSource.setTestOnBorrow(true);
        DynamicDatasouce dynamicDatasouce = new DynamicDatasouce();
        dynamicDatasouce.setTargetDataSources(Collections.emptyMap());
        dynamicDatasouce.setDefaultTargetDataSource(dataSource);
        return dynamicDatasouce;
    }

    @Bean
    public ServletRegistrationBean druidStatViewServlet() {
        @SuppressWarnings("unchecked")
        ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
        servletRegistrationBean.addInitParameter("allow", "127.0.0.1");
        servletRegistrationBean.addInitParameter("loginUsername", "test");
        servletRegistrationBean.addInitParameter("loginPassword", "123456");
        return servletRegistrationBean;
    }

    @Bean
    public FilterRegistrationBean druidStatFilter() {
        @SuppressWarnings("unchecked")
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new WebStatFilter());
        filterRegistrationBean.setName("druidWebStatFilter");
        filterRegistrationBean.addUrlPatterns("/*");
        filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
        return filterRegistrationBean;
    }

}